﻿Option Explicit On


'*******************************************************************
' Program: pkgVisio
' Author: Albert E Edlund
' Date:
'
' Purpose:
' Comments/Base: 

'*******************************************************************

#Region " imports "

Imports System
Imports System.IO
Imports System.IO.Packaging
Imports System.Windows.Forms


Imports System.Xml
Imports System.Linq

Imports System.Collections
Imports System.Collections.Generic
Imports System.Collections.ObjectModel

Imports Microsoft.Practices.EnterpriseLibrary.Common
Imports Microsoft.Practices.EnterpriseLibrary.ExceptionHandling
Imports Microsoft.Practices.EnterpriseLibrary.ExceptionHandling.Logging

Imports <xmlns="http://schemas.microsoft.com/office/visio/2012/main">

Imports pkgVisio.clsVisPackage

Imports System.Text
Imports System.Xml.Schema
Imports System.Xml.XmlReader
Imports pkgVisio.clsStructures

#End Region



Public Class frmDataRecordsets



#Region " Properties and Declarations "

    ' the local class definitions
    Private m_visPackage As clsVisPackage
    Public Property visPackage As clsVisPackage
        Get
            visPackage = Me.m_visPackage
        End Get
        Set(value As clsVisPackage)
            If (value Is Nothing) Then
                Throw New System.ArgumentNullException("Value", _
                    "visPackage is Null.")
            End If
            Me.m_visPackage = value
        End Set
    End Property

    Private m_visRecordsets As clsRecordsets
    Public Property visRecordsets As clsRecordsets
        Get
            visRecordsets = Me.m_visRecordsets
        End Get
        Set(value As clsRecordsets)

        End Set
    End Property

    Private m_visDataConnections As clsConnections
    Public Property visDataConnections As clsConnections
        Get
            visDataConnections = Me.m_visDataConnections
        End Get
        Set(value As clsConnections)
            Me.m_visDataConnections = value
        End Set
    End Property

    Private m_visRecordset As clsRecordset
    Public Property visRecordset As clsRecordset
        Get
            visRecordset = Me.m_visRecordset
        End Get
        Set(value As clsRecordset)
            Me.m_visRecordset = value
        End Set
    End Property




    Private m_colPkgPartInfo As Collection(Of pkgpartInfo)
    Public Property colPkgPartInfo As Collection(Of pkgpartInfo)
        Get
            colPkgPartInfo = m_colPkgPartInfo
        End Get
        Set(value As Collection(Of pkgpartInfo))
            If (value Is Nothing) Then
                Throw New System.ArgumentNullException("Value", _
                    "colPkgPartsInfo is Null.")
            End If
            m_colPkgPartInfo = value
        End Set
    End Property

    Private m_currRsId As Long
    Public Property currRsId As Long
        Get
            currRsId = Me.m_currRsId
        End Get
        Set(value As Long)
            Me.m_currRsId = value
        End Set
    End Property

    Private _lngRsId As Long
    Public Property lngRsId As Long
        Get
            lngRsId = _lngRsId
        End Get
        Set(value As Long)
            _lngRsId = value
        End Set
    End Property

    Private _lngRsConnId As Long
    Public Property lngRsConnId As Long
        Get
            lngRsConnId = _lngRsConnId
        End Get
        Set(value As Long)
            _lngRsConnId = value
        End Set
    End Property

    Private _strRsName As String
    Public Property strRsName As String
        Get
            strRsName = _strRsName
        End Get
        Set(value As String)
            _strRsName = value
        End Set
    End Property

    Private Property strDcFileName As String

#End Region

#Region " Methods "




    '
    ' this is step two for setting up the form
    '
    ' the connections file should be relatively short
    '
    Private Sub buildDataConnections()

        Try

            If visDataConnections IsNot Nothing Then
                Me.m_visDataConnections = Nothing
            End If

            Me.visDataConnections = New clsConnections

            If Me.visDataConnections.colPkgPartInfo Is Nothing Then
                Me.visDataConnections.colPkgPartInfo = New Collection(Of pkgpartInfo)
            End If
            Me.visDataConnections.colPkgPartInfo.Clear()
            Me.visDataConnections.colPkgPartInfo = Me.visPackage.colPkgPartInfo

            Dim colPkgParts As Collection(Of pkgpartInfo) = New Collection(Of pkgpartInfo)
            colPkgParts.Clear()

            colPkgParts = Me.visPackage.getPkgPartsByContent(pkgVisio.clsVisPackage.contXmlConnections)
            If colPkgParts.Count = 1 _
                And Me.visPackage.colPkgPartInfo.Count <> 0 Then
                Dim pkgInfo As pkgpartInfo = colPkgParts(0)
                Me.visDataConnections.xDoc = Me.visPackage.getPackagePartAsXDoc(Me.visPackage.fileCurrent, pkgInfo)
                Me.visDataConnections.loadDataConnections(Nothing)
            Else
                Me.StatusStrip1.Text = "No Connections PackagePart Found"
            End If


        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

    End Sub

    '
    ' this is the third step in setting up the form
    '
    Private Sub buildDataRecordsets()

        Try

            If Me.m_visRecordsets IsNot Nothing Then
                Me.m_visRecordsets = Nothing
            End If

            Me.m_visRecordsets = New clsRecordsets

            If Me.visRecordsets.colPkgPartInfo Is Nothing Then
                Me.visRecordsets.colPkgPartInfo = New Collection(Of pkgpartInfo)
            End If
            ' Dim xDoc As XDocument = New XDocument
            Me.visRecordsets.colPkgPartInfo.Clear()
            Me.visRecordsets.colPkgPartInfo = Me.visPackage.colPkgPartInfo


            Me.visRecordsets.visPackage = Me.visPackage


            ' get the package parts for the visRecordsets
            Dim colPkgParts As Collection(Of pkgpartInfo) = New Collection(Of pkgpartInfo)

            colPkgParts = Me.visPackage.getPkgPartsByContent(pkgVisio.clsVisPackage.contXmlRecordsets)



            If colPkgParts.Count = 1 Then
                Dim pkgInfo As pkgpartInfo = colPkgParts(0)
                Me.visRecordsets.xDoc = Me.visPackage.getPackagePartAsXDoc(Me.visPackage.fileCurrent, pkgInfo)
                Me.visRecordsets.loadDataRecordSets(Me.lvAdoRecordsets)
            End If

            If Me.visRecordsets.colRecordsets.Count > 0 Then
                Dim rsFirst As clsRecordsets.itemRecordset = New clsRecordsets.itemRecordset(-1, -1, "", "", "", "")
                rsFirst = visRecordsets.colRecordsets(0)
                currRsId = CLng(rsFirst.rsId)
                Me.StatusStrip1.Text = CStr(rsFirst.rsId)
            End If


        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

    End Sub

    '
    ' 
    '
    Private Sub getDataRecordSetInfo(ByVal lngId As Long)



        Try



            Dim qryRecordsets = Me.visRecordsets.xDoc...<DataRecordSet>
            Dim intRecordsets As Integer = qryRecordsets.Count

            Me.txtDcCommand.Text = ""
            Me.txtDcConnectionString.Text = ""
            Me.txtDcFileName.Text = ""
            Dim strRsCmd As String = ""

            For Each recordset In qryRecordsets

                lngRsId = -1
                lngRsConnId = -1
                strRsName = "NoName"
                strRsCmd = "NoCmd"
                Me.txtSchema.Text = ""


                Dim listOfAttributes As IEnumerable(Of XAttribute) = _
                    From att In recordset.Attributes() _
                    Select att
                For Each att As XAttribute In listOfAttributes
                    ' Console.WriteLine("{0}={1}", att.Name.LocalName, att.Value)
                    Select Case LCase(att.Name.LocalName)
                        Case "id"
                            lngRsId = CLng(att.Value)
                        Case "name"
                            ' get the recordset name
                            strRsName = CStr(att.Value)
                        Case "connectionid"
                            lngRsConnId = CLng(att.Value)
                        Case "command"
                            strRsCmd = att.Value
                    End Select
                Next att


                If lngRsId = lngId Then

                    Dim tempColPkgPartInfo As Collection(Of pkgpartInfo) = Me.visPackage.colPkgPartInfo

                    loadDataRecordsetClass()
                    loadRowMapListView()

                    Me.txtDcCommand.Text = strRsCmd

                    If Me.visDataConnections IsNot Nothing Then
                        If Me.visDataConnections.dictDataConn.ContainsKey(lngRsConnId) Then
                            Dim tempStc As clsConnections.dataConn = New clsConnections.dataConn
                            tempStc = Me.visDataConnections.dictDataConn.Item(lngRsConnId)
                            Dim strConn As String = tempStc.connString
                            Me.txtDcFileName.Text = tempStc.connFile
                            Me.txtDcConnectionString.Text = Me.visDataConnections.readConnectionString(strConn)
                        End If
                    End If

                    Exit For
                End If

                'getDataColumnSet(recordset)

            Next recordset



        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

    End Sub


    '
    ' look at the currRsId and load the appropriate recordset package part
    '
    Private Sub loadDataRecordsetClass()


        Try

            If Me.m_visRecordset IsNot Nothing Then
                Me.m_visRecordset = Nothing
            End If
            visRecordset = New clsRecordset

            Dim strRsFile As String = ""
            Dim itemRS As clsRecordsets.itemRecordset
            For Each itemRS In Me.visRecordsets.colRecordsets
                If CLng(itemRS.rsId) = currRsId Then
                    strRsFile = itemRS.rsFile
                    Me.visRecordset.lngRsConnId = itemRS.rsConnId
                    Me.visRecordset.strRsName = itemRS.rsName
                    Me.visRecordset.lngRsId = itemRS.rsId

                    ' Dim xDoc As XDocument = New XDocument
                    Me.visRecordset.colPkgPartInfo.Clear()
                    ' load the package part location data
                    If Me.visPackage.colPkgPartInfo.Count = 0 Then
                        Me.visPackage.loadPkgAndParts()
                    End If
                    Me.visRecordset.colPkgPartInfo = Me.visPackage.colPkgPartInfo

                    Using CurrentPackage As Package = Package.Open(Me.visPackage.fileCurrent, FileMode.Open, FileAccess.Read)

                        Dim part As PackagePart = CurrentPackage.GetPart(New Uri(strRsFile, UriKind.Relative))
                        '  Load the document XML in the part into an XDocument instance.

                        Me.visRecordset.m_xDoc = Nothing
                        Me.visRecordset.xDoc = New XDocument
                        Me.visRecordset.xDoc = XDocument.Load(XmlReader.Create(part.GetStream()))

                        Me.visRecordset.loadAdoDataToDataGridView(Me.dgvDataRows)
                        Dim strSchema As String = ""
                        strSchema = Me.visRecordset.getAdoSchemaFromXDoc(visRecordset.xDoc)
                        Me.txtSchema.Text = strSchema

                        CurrentPackage.Close()

                    End Using

                    Exit For
                End If ' test for rsId = strRsId
            Next itemRS

        Catch errXml As XmlException
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(errXml, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

    End Sub

    '
    '
    '
    Private Sub loadRowMapListView()


        Try

            Dim qryRecordset = From rsSel In Me.visRecordsets.xDoc...<DataRecordSet>
                               Where rsSel.@ID = CStr(currRsId)
            If qryRecordset.Count = 1 Then
                Me.visRecordsets.loadRowMapListView(qryRecordset.First, lvRowMap)
                Me.visRecordsets.loadDataColumnListView(qryRecordset.First, Me.lvColumns)
            End If

        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try


    End Sub



#End Region

    '
    '
    '
    Public Sub New()

        ' This call is required by the designer.
        InitializeComponent()

        ' Add any initialization after the InitializeComponent() call.

        If Me.m_visPackage Is Nothing Then
            Me.m_visPackage = New clsVisPackage
        End If

        If Me.m_visRecordsets Is Nothing Then
            Me.m_visRecordsets = New clsRecordsets
        End If

        If Me.m_visRecordset Is Nothing Then
            Me.m_visRecordset = New clsRecordset
        End If

        If Me.m_visDataConnections Is Nothing Then
            Me.m_visDataConnections = New clsConnections
        End If

        If Me.m_colPkgPartInfo Is Nothing Then
            Me.m_colPkgPartInfo = New Collection(Of pkgpartInfo)
        End If

        Me.StatusStrip1.Text = CStr(currRsId)

    End Sub

    '
    '
    '
    Protected Overrides Sub Finalize()

        If Me.m_visPackage IsNot Nothing Then
            Me.m_visPackage = Nothing
        End If

        If Me.m_visRecordsets IsNot Nothing Then
            Me.m_visRecordsets = Nothing
        End If

        If Me.m_visRecordset IsNot Nothing Then
            Me.m_visRecordset = Nothing
        End If

        If Me.m_visDataConnections IsNot Nothing Then
            Me.m_visDataConnections = New clsConnections
        End If

        If Me.m_colPkgPartInfo IsNot Nothing Then
            Me.m_colPkgPartInfo.Clear()
            Me.m_colPkgPartInfo = Nothing
        End If

        MyBase.Finalize()

    End Sub

    '
    '
    '
    Private Sub lvAdoRecordsets_SelectedIndexChanged(sender As System.Object, e As System.EventArgs) Handles lvAdoRecordsets.SelectedIndexChanged

        Dim rsItems As ListView.SelectedListViewItemCollection = lvAdoRecordsets.SelectedItems
        Dim rsItem As ListViewItem
        Dim rsSubItem As ListViewItem.ListViewSubItem

        If 0 < rsItems.Count Then
            rsItem = rsItems(0)
            rsSubItem = rsItem.SubItems(1)
            currRsId = CLng(rsSubItem.Text)

            getDataRecordSetInfo(CLng(rsSubItem.Text))

        End If

    End Sub

    '
    '
    '
    Private Sub ExitToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles ExitToolStripMenuItem.Click
        Me.Close()
    End Sub

    '
    '
    '
    Private Sub AboutToolStripMenuItem_Click(sender As System.Object, e As System.EventArgs) Handles AboutToolStripMenuItem.Click
        frmAbout.ShowDialog()
    End Sub

    '
    '
    '
    Private Sub frmDataRecordsets_FormClosed(sender As Object, e As System.Windows.Forms.FormClosedEventArgs) Handles Me.FormClosed

        ' cleanup

        If Me.m_visPackage IsNot Nothing Then
            Me.m_visPackage = Nothing
        End If

        If Me.m_visRecordsets IsNot Nothing Then
            Me.m_visRecordsets = Nothing
        End If

        If Me.m_visRecordset IsNot Nothing Then
            Me.m_visRecordset = Nothing
        End If

        If Me.m_visDataConnections IsNot Nothing Then
            Me.m_visDataConnections = New clsConnections
        End If

        If Me.m_colPkgPartInfo IsNot Nothing Then
            Me.m_colPkgPartInfo.Clear()
            Me.m_colPkgPartInfo = Nothing
        End If


    End Sub


    '
    '
    '
    Private Sub frmDataRecordsets_Shown(sender As Object, e As System.EventArgs) Handles Me.Shown
        Try

            ' clear the local classes
            If Me.m_visPackage Is Nothing Then
                Me.m_visPackage = New clsVisPackage
            Else
                Me.m_visPackage = Nothing
                Me.m_visPackage = New clsVisPackage
            End If

            If Me.m_visRecordsets Is Nothing Then
                Me.m_visRecordsets = New clsRecordsets
            Else
                Me.m_visRecordsets = Nothing
                Me.m_visRecordsets = New clsRecordsets
            End If

            If Me.m_visRecordset Is Nothing Then
                Me.m_visRecordset = New clsRecordset
            Else
                Me.m_visRecordset = Nothing
                Me.m_visRecordset = New clsRecordset
            End If

            If Me.m_visDataConnections Is Nothing Then
                Me.m_visDataConnections = New clsConnections
            Else
                Me.m_visDataConnections = Nothing
                Me.m_visDataConnections = New clsConnections
            End If

            If Me.m_colPkgPartInfo Is Nothing Then
                Me.m_colPkgPartInfo = New Collection(Of pkgpartInfo)
            Else
                Me.m_colPkgPartInfo = Nothing
                Me.m_colPkgPartInfo = New Collection(Of pkgpartInfo)
            End If

            ' clear the controls
            Me.m_currRsId = -1
            Me.lvAdoRecordsets.Clear()
            Me.dgvDataRows.DataSource = Nothing
            Me.dgvDataRows.DataMember = Nothing
            Me.txtDcCommand.Text = ""
            Me.txtDcConnectionString.Text = ""
            Me.txtDcFileName.Text = ""
            Me.txtSchema.Text = ""
            Me.lvColumns.Clear()
            Me.lvRowMap.Clear()

            Me.StatusStrip1.Text = CStr(currRsId)


            Dim frmParent As frmMain = Nothing
            If Me.Owner IsNot Nothing Then
                ' should be frmMain
                frmParent = Me.Owner
                Me.visPackage = frmParent.visPackage
                Me.visPackage.loadPkgAndParts()

            End If

            ' build the primary dictionaries for page and shape information
            If Me.visPackage.dictPageShape.Count = 0 Then
                Me.StatusStrip1.Text = " start build page "
                Me.visPackage.buildPageAndShapeDictionaries()
                If frmParent IsNot Nothing Then
                    frmParent.visPackage.dictPagesID = Me.visPackage.dictPagesID
                    frmParent.visPackage.dictPageShape = Me.visPackage.dictPageShape
                End If ' test for frmparent
            End If

            If Me.visDataConnections.dictDataConn.Count = 0 Then
                Me.StatusStrip1.Text = " start build connections "
                ' read the datarecordsets file and prep the listview control
                buildDataConnections()
            End If

            Me.StatusStrip1.Text = " start build data recordsets "
            If Me.colPkgPartInfo.Count = 0 Then
                Me.visPackage.fileCurrent = frmParent.strPackagePath
                Me.visPackage.loadPkgAndParts()
            End If

            buildDataRecordsets()


        Catch err As Exception
            Dim rethrow As Boolean = ExceptionPolicy.HandleException(err, "Log Only Policy")
            If (rethrow) Then
                Throw
            End If
        End Try

    End Sub



End Class